package com.javachmapi.service.impl;

import cn.hutool.core.date.DateUtil;
import com.javachmapi.entity.User;
import com.javachmapi.entity.UserToken;
import com.javachmapi.dao.UserTokenDao;
import com.javachmapi.service.UserTokenService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (UserToken)表服务实现类
 *
 * @author 宋利军
 * @since 2020-11-09 02:50:10
 */
@Service("userTokenService")
public class UserTokenServiceImpl implements UserTokenService {
    @Resource
    private UserTokenDao userTokenDao;

    /**
     * 新增数据
     *
     * @param userToken 实例对象
     * @return 实例对象
     */
    public UserToken insert(UserToken userToken) {
        this.userTokenDao.insert(userToken);
        return userToken;
    }

    /**
     * 通过主键删除数据
     *
     * @param token 主键
     * @return 是否成功
     */
    public boolean deleteById(String token) {
        return this.userTokenDao.deleteById(token) > 0;
    }

    public UserToken check(User user) {
        if(user == null) {
            return null;
        }
        //找到旧的登录状，并删除
        UserToken token = this.userTokenDao.findUserId(user.getId());;
        if(token != null) {
            this.userTokenDao.deleteById(token.getToken());
        }
        token = new UserToken();
        token.setToken(DigestUtils.md5Hex("token"+user.getUsername()+System.currentTimeMillis()));
        token.setUserId(user.getId());
        token.setCreateDate(new Date());
        token.setExpiretime(DateUtil.nextMonth());
        this.userTokenDao.insert(token);
        return token;
    }
}